﻿using System;
using System.Collections;
using System.Collections.Generic;
using Common.Input;
using UnityEngine;

namespace Challenge
{
    public class DragAndMoveDetector : MonoBehaviour
    {
        public Camera camera;
        private Transform selectorTrans;

        void Start()
        {
            InputController.instance.pressed += OnPress;
            InputController.instance.dragged += OnDrag;
        }

        private void OnDestroy()
        {
            if (InputController.instanceExists)
            {
                InputController.instance.pressed -= OnPress;
                InputController.instance.dragged -= OnDrag;
            }
        }

        private void OnPress(PointerActionInfo pinfo)
        {
            var mousePosInWorld = camera.ScreenToWorldPoint(pinfo.currentPosition);
            RaycastHit2D hit =
                Physics2D.Raycast(new Vector2(mousePosInWorld.x, mousePosInWorld.y), Vector3.forward, 10f);
            if (hit)
            {
                selectorTrans = hit.transform;
            }
        }

        private void OnDrag(PointerActionInfo pinfo)
        {
            if (selectorTrans)
            {
                var pos = selectorTrans.position;
                var previosMousePos = camera.ScreenToWorldPoint(pinfo.previousPosition);
                var curMousePos = camera.ScreenToWorldPoint(pinfo.currentPosition);
                var deltaPos = curMousePos - previosMousePos;
                var curPos = pos + new Vector3(deltaPos.x, deltaPos.y);
                selectorTrans.position = curPos;
            }
        }
    }
}